﻿using AutoMapper;
using BW.MesProject.Public.Domain.RBAC;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using BW.MesProject.WareHouse.Domain;
using BW.MesProject.WareHouse.Infrastructure;
using BW.MesProject.WareHouse.Infrastructure.Dto.Input;
using BW.MesProject.WareHouse.Infrastructure.Dto.OutPut;
using Dm.util;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace BW.MesProject.WareHouse.Application
{
    public class ShelvesServices : IShelvesServices
    {
        private readonly IBaseRepository<ShelvesModel> _Shelves;
        private readonly IBaseRepository<EMPModel> _Emp;
        private readonly IMapper _mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="Shelves"></param>
        /// <param name="mapper"></param>
        public ShelvesServices(IBaseRepository<EMPModel> Emp, IBaseRepository<ShelvesModel> Shelves, IMapper mapper)
        {
            _Emp = Emp;
            _Shelves = Shelves;
            this._mapper = mapper;
        }
        /// <summary>
        /// 新增货架/库区
        /// </summary>
        /// <param name="shelvesModel"></param>
        /// <returns></returns>
        public ApiResult<int> AddShelves(ShelvesModel shelvesModel)
        {


            //判断货架/库区编码，名称。所属仓库是否为空
            if (string.IsNullOrEmpty(shelvesModel.Shelvesid) || string.IsNullOrEmpty(shelvesModel.Shelvesname) || string.IsNullOrEmpty(shelvesModel.WHId.toString()))
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "请检查货架/库区的编号、名称、所属仓库否为空"
                };
            }
            var model = _Shelves.GetValue(x => x.Shelvesid == shelvesModel.Shelvesid);
            if (model != null && !string.IsNullOrEmpty(model.Shelvesid))
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "货架/库区编号重复，请重新检查修改！！！"
                };
            }
            model = _Shelves.GetValue(x => x.Shelvesname == shelvesModel.Shelvesname);
            if (model != null && !string.IsNullOrEmpty(model.Shelvesname))
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "货架/库区名称重复，请重新检查修改！！！"
                };
            }
            shelvesModel.SHId = YitIdHelper.NextId();
            //添加
            var models = _mapper.Map<ShelvesModel>(shelvesModel);

            return new ApiResult<int>
            {
                Code = ApiEnums.Success,
                Message = "添加成功",
                Data = _Shelves.Add(shelvesModel),
            };
        }

        /// <summary>
        /// 删除货架/库区
        /// </summary>
        /// <param name="Id">货架/库区主键ID</param>
        /// <returns>操作结果</returns>
        public ApiResult<int> DeleteShelves(long Id)
        {
            // 参数验证
            if (Id == 0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "无效的货架/库区ID",
                    Data = 0,
                    TotalCount = 0
                };
            }

            try
            {
                // 根据id查询货架/库区信息
                var model = _Shelves.GetValue(x => x.SHId == Id);


                // 检查是否存在
                if (model == null)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "未找到指定的货架/库区信息",
                        Data = 0,
                        TotalCount = 0
                    };
                }

                // 删除前检查是否有关联的库位等信息
                // TODO: 如果有其他关联表，需要检查是否有关联数据

                // 执行删除操作
                int result = _Shelves.Delete(model);

                if (result > 0)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Success,
                        Message = "删除成功",
                        Data = result,
                        TotalCount = 0
                    };
                }
                else
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "删除失败",
                        Data = 0,
                        TotalCount = 0
                    };
                }
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"删除货架/库区时发生异常: {ex.Message}");

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"删除失败: {ex.Message}",
                    Data = 0,
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 查询货架/库区
        /// </summary>
        /// <param name="qryInput"></param>
        /// <returns></returns>
        public ApiResult<List<ShelvesOut>> GetShelves(QryInput qryInput)
        {
            int totalCount = 0;
            //查询名称来显示数据
            var list = _Shelves.GetAll().Where(x => x.IsDeleted == false);
            if (qryInput.PageSize == 0)
            {

                list = list.Where(x => x.IsEnable == true).OrderBy(u => u.CreatedTime);
            }
            else
            {

                // 按编码查询
                if (!string.IsNullOrEmpty(qryInput.QryID) && !string.IsNullOrEmpty(qryInput.QryName))
                {
                    list = list.Where(x => x.Shelvesid.Contains(qryInput.QryID) && x.Shelvesname.Contains(qryInput.QryName));
                }
                else if (!string.IsNullOrEmpty(qryInput.QryID))
                {
                    list = list.Where(x => x.Shelvesid.Contains(qryInput.QryID));
                }
                else if (!string.IsNullOrEmpty(qryInput.QryName))
                {
                    list = list.Where(x => x.Shelvesname.Contains(qryInput.QryName));
                }


            }
            // 处理结果数据
            var result = new List<ShelvesOut>();

            // 联表查询仓库，人员名称等信息
            var query1 = list.LeftJoin<WarehouseModel>((a, b) => a.WHId == b.WHId).LeftJoin<UserModel>((a, b, c) => a.CreatedBy == c.UserId).Select((a, b, c) =>
                 new ShelvesOut
                 {
                     SHId = a.SHId,//主键ID
                     WHId = a.WHId,
                     Warehouseid = b.Warehouseid,//仓库ID
                     WarehouseName = b.Warehousename,//仓库名称
                     Shelvesid = a.Shelvesid,//库位编码
                     Shelvesname = a.Shelvesname,//库位名称
                     Memo = a.Memo,//描述
                     EMPID = c.UserId,
                     EMPName = c.UserName,
                     CreatedBy = a.CreatedBy,
                     CreatedTime = a.CreatedTime, 
                     UpdatedTime = a.UpdatedTime,
                     IsDeleted=a.IsDeleted,
                     IsEnable=a.IsEnable
                 });

            var queryList = query1?.ToList();


            // 计算总数量
            totalCount = queryList.Count();

            // 分页处理
            if (qryInput.PageSize > 0)
            {
                queryList = queryList
                    .OrderBy(a => a.Shelvesid).ThenBy(x => x.CreatedTime)
                    .Skip((qryInput.PageNum - 1) * qryInput.PageSize)
                    .Take(qryInput.PageSize)
                    .ToList();
            }

            return new ApiResult<List<ShelvesOut>>()
            {
                Code = ApiEnums.Success,
                Message = "查询成功",
                Data = queryList,
                TotalCount = totalCount,
                PageNum = qryInput.PageNum,
                PageSize = qryInput.PageSize
            };
        }



        /// <summary>
        /// 修改货架/库区
        /// </summary>
        /// <param name="model">货架/库区信息</param>
        /// <returns>操作结果</returns>
        public ApiResult<int> UpdateShelves(ShelvesModel model)
        {
            try
            {
                //根据id查询是否有这条数据没有就修改不了
                var query = _Shelves.GetValue(x => x.Shelvesid == model.Shelvesid);
                if (query == null)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "修改失败，未找到指定的货架/库区信息",
                        Data = 0,
                        TotalCount = 0
                    };
                }

                //保存添加人和添加时间，添加修改人和修改时间
                _Shelves.Update(model);

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Success,
                    Message = "修改成功",
                    Data = 1,
                    TotalCount = 0
                };
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"修改货架/库区时发生异常: {ex.Message}");

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"修改失败: {ex.Message}",
                    Data = 0,
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 修改启用
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateEnable(ShelvesModel model)
        {
            var IsEnable = model.IsEnable;
            //根据id修改逻辑删除为 false
            model = _Shelves.GetValue(x => x.SHId == model.SHId);
            model.IsEnable = IsEnable;
            var Message = string.Empty;
            if (IsEnable)
            {
                Message = "启用成功";
            }
            else
            {
                Message = "停用成功";
            }
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = Message,
                Data = _Shelves.Update(model),
                TotalCount = 0
            };

        }

        /// <summary>
        /// 软删除（修改状态）
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateDelete(long Id)
        {
            //根据id修改逻辑删除为 false
           var model = _Shelves.GetValue(x => x.SHId == Id);
            model.IsDeleted = true;
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "删除成功",
                Data = _Shelves.Update(model),
                TotalCount = 0
            };

        }

        /// <summary>
        /// 查询表是否有该编码
        /// </summary>
        /// <param name="Shelvesid"></param>
        /// <returns></returns>
        public ApiResult<int> GetShelvesID(string Shelvesid)
        {
            var model = _Shelves.GetValue(x => x.Shelvesid == Shelvesid);
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "成功",
                Data = 1,
                TotalCount = 0
            };

        }
    }
}
